package com.angcyo.javafx.base

import com.angcyo.javafx.annotation.inject
import com.angcyo.javafx.base.ex.getStage
import com.angcyo.javafx.base.ex.onLater
import com.angcyo.library.ex.className
import com.angcyo.log.L
import javafx.fxml.Initializable
import javafx.scene.Node
import javafx.stage.Stage
import java.net.URL
import java.util.*

/**
 * Email:angcyo@126.com
 * @author angcyo
 * @date 2020/12/25
 */
open class BaseController : Initializable {

    companion object {
        val controllerHolder = hashMapOf<Class<*>, BaseController>()
    }

    /**舞台*/
    var stage: Stage? = null

    /**初始化控制器*/
    override fun initialize(location: URL?, resources: ResourceBundle?) {
        L.i("${className()} initialize:$location $resources")
        controllerHolder[this.javaClass] = this

        if (stage == null) {
            //stage 刚创建的node还不会立马绑定舞台, 需要延迟一下
            onLater {
                _checkStage()
                initStage()
            }
        }
    }

    /**子页面(TAB中的页面)初始化控制器
     * */
    open fun initialize(stage: Stage?, location: URL?, resources: ResourceBundle?) {
        this.stage = stage
        initStage()
        initialize(location, resources)
    }

    fun _checkStage() {
        if (stage == null) {
            for (field in this::class.java.declaredFields) {
                try {
                    field.isAccessible = true
                    if (Node::class.java.isAssignableFrom(field.type)) {
                        val node = field.get(this)
                        if (node != null) {
                            stage = (node as Node).getStage()
                        }
                        if (stage != null) {
                            break
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    open fun initStage() {
        //节点注入 [NodeInject]
        inject(stage)

        stage?.apply {
            if (onCloseRequest == null) {
                setOnCloseRequest {
                    //it.consume()
                    destroy()
                }
            }
        }
    }

    fun closeStage() {
        stage?.apply {
            close()
            destroy()
        }
    }

    /**销毁控制器*/
    fun destroy() {
        L.i("${className()} destroy.")
        controllerHolder.remove(this.javaClass)
    }
}